
import torch
import torch.nn as nn
import math
from torch.nn import functional as F

# 定义一个简单的嵌入层
class EmbeddingLayer(nn.Module):
    def __init__(self, vocab_size, d_model):
        super(EmbeddingLayer, self).__init__()
        self.embedding = nn.Embedding(vocab_size, d_model)
 
    def forward(self, x):
        return self.embedding(x)
 
vocab_size = 10000  # 假设词表大小
# 随机生成一个输入序列
input_seq = torch.randint(0, vocab_size, (32, 50))  # (batch_size, seq_len)
print(input_seq)
# 获取输入表示
# 创建嵌入层实例
# 假设d_model的值为512
d_model = 512
embedding_layer = EmbeddingLayer(vocab_size, d_model)
input_repr = embedding_layer(input_seq)
print(input_repr)

class Attention(nn.Module):
    def __init__(self, embed_dim):
        super(Attention, self).__init__()
        self.query = nn.Linear(embed_dim, embed_dim)
        self.key = nn.Linear(embed_dim, embed_dim)
        self.value = nn.Linear(embed_dim, embed_dim)
 
    def forward(self, x):
        Q = self.query(x)
        K = self.key(x)
        V = self.value(x)
 
        attention_scores = torch.matmul(Q, K.transpose(-1, -2)) / math.sqrt(embed_dim)
        attention_weights = F.softmax(attention_scores, dim=-1)
 
        return attention_weights